# -*-coding:utf-8 -*-
from django.shortcuts import render
from content.api.serializers import *
from content.models import *
from rest_framework import generics, viewsets
from rest_framework import renderers
from core.api.views import HtmlModelViewSet, DynamicFieldsViewMixin
from django_filters import rest_framework as filters
from rest_framework.decorators import action
from asset.models import Device
from django.db.models import Q


class BaseContentFilter(filters.FilterSet):
    class Meta:
        model = Content
        fields = {
            'department': ['exact'],
            'category': ['exact', 'in'],
            'published': ['exact'],
        }


class ContentApiViewSet(DynamicFieldsViewMixin, viewsets.ReadOnlyModelViewSet):
    """
    全部内容
    """
    queryset = Content.objects.all()
    serializer_class = ContentSerializer
    #permission_classes = (IsAdminUser,)
    ordering_fields = ('spinyin', 'publishdate')
    search_fields = ('subject', 'summary')
    filter_class = BaseContentFilter
    def get_object(self):
        obj = super().get_object()
        read_count_add(obj)
        return obj

    def get_queryset(self):
        qs = super().get_queryset()
        device = self.request.query_params.get('device', None)
        if device:
            dev = Device.objects.get(pk=device)
            qs = qs.filter(Q(department=dev.department) | Q(department__isnull=True)).filter(Q(aimboxs__in=[dev]) | Q(aimboxs=None))
        return qs


class HowToGoApiViewSet(DynamicFieldsViewMixin, viewsets.ModelViewSet):
    """
    办公区引导
    """
    queryset = HowToGo.objects.all()
    serializer_class = HowToGoSerializer
    #permission_classes = (IsAdminUser,)
    ordering_fields = ('order', )
    search_fields = ('title',)
    filter_fields = ('department',)

    def get_object(self):
        obj = super().get_object()
        read_count_add(obj)
        return obj

    def get_queryset(self):
        qs = super().get_queryset()
        device = self.request.query_params.get('device', None)
        if device:
            dev = Device.objects.get(pk=device)
            qs = qs.filter(Q(department=dev.department) | Q(department__isnull=True)).filter(Q(aimboxs__in=[dev]) | Q(aimboxs=None))
        return qs

    # 创建前处理
    # def perform_create(self, serializer):
    #    serializer.save(from_personnel=personnel)


class NewsAPIView(DynamicFieldsViewMixin, HtmlModelViewSet):
    """
    新闻资讯
    """
    queryset = News.objects.all()
    serializer_class = NewsSerializer
    renderer_classes = (renderers.BrowsableAPIRenderer, renderers.TemplateHTMLRenderer, renderers.JSONRenderer)
    ordering_fields = ('spinyin', 'publishdate')
    search_fields = ('subject', 'summary')
    filter_fields = ('department', 'category', 'published')
    #template_name = "content/api/notice_detail.html"
    detail_template_name = "content/api/news_detail.html"
    ordering = ["-published"]

    def get_object(self):
        obj = super().get_object()
        read_count_add(obj)
        return obj

    def get_queryset(self):
        qs = super().get_queryset()
        device = self.request.query_params.get('device', None)
        if device:
            dev = Device.objects.get(pk=device)
            qs = qs.filter(Q(department=dev.department) | Q(department__isnull=True)).filter(Q(aimboxs__in=[dev]) | Q(aimboxs=None))
        return qs

    # 创建前处理
    def perform_create(self, serializer):
        serializer.save(createdby=self.request.user)

    @action(methods=["GET"], detail=False)
    def published(self, request):
        '''
        新闻资讯已发布
        '''
        self.queryset = News.objects.published()
        return self.list(request)


class NoticeAPIView(DynamicFieldsViewMixin, HtmlModelViewSet):
    """
    通知
    """
    queryset = Notice.objects.all()
    serializer_class = NoticeSerializer
    #permission_classes = (IsAdminUser,)
    renderer_classes = (renderers.BrowsableAPIRenderer, renderers.TemplateHTMLRenderer, renderers.JSONRenderer)
    ordering_fields = ('spinyin', 'publishdate')
    search_fields = ('subject', 'summary')
    filter_fields = ( 'department', 'category', 'published')
    #template_name = "content/api/notice_detail.html"
    detail_template_name = "content/api/notice_detail.html"
    ordering = ["-published"]

    def get_object(self):
        obj = super().get_object()
        read_count_add(obj)
        return obj

    def get_queryset(self):
        qs = super().get_queryset()
        device = self.request.query_params.get('device', None)
        if device:
            dev = Device.objects.get(pk=device)
            qs = qs.filter(Q(department=dev.department) | Q(department__isnull=True)).filter(Q(aimboxs__in=[dev]) | Q(aimboxs=None))
        return qs

    # 创建前处理
    def perform_create(self, serializer):
        serializer.save(createdby=self.request.user)

    @action(methods=["GET"], detail=False)
    def published(self, request):
        '''
        通知已发布
        '''
        self.queryset = Notice.objects.published()
        return self.list(request)


class NotifyAPIView(DynamicFieldsViewMixin, HtmlModelViewSet):
    """
    公告
    """
    queryset = Notify.objects.all()
    serializer_class = NotifySerializer
    #permission_classes = (IsAdminUser,)
    renderer_classes = (renderers.BrowsableAPIRenderer, renderers.TemplateHTMLRenderer, renderers.JSONRenderer)
    ordering_fields = ('spinyin', 'publishdate')
    search_fields = ('subject', 'summary')
    filter_fields = ( 'department', 'category', 'published')
    #template_name = "content/api/notice_detail.html"
    detail_template_name = "content/api/notify_detail.html"
    ordering = ["-published"]

    def get_object(self):
        obj = super().get_object()
        read_count_add(obj)
        return obj

    def get_queryset(self):
        qs = super().get_queryset()
        device = self.request.query_params.get('device', None)
        if device:
            dev = Device.objects.get(pk=device)
            qs = qs.filter(Q(department=dev.department) | Q(department__isnull=True)).filter(Q(aimboxs__in=[dev]) | Q(aimboxs=None))
        return qs

    # 创建前处理
    def perform_create(self, serializer):
        serializer.save(createdby=self.request.user)

    @action(methods=["GET"], detail=False)
    def published(self, request):
        '''
        公告已发布
        '''
        self.queryset = Notify.objects.published()
        return self.list(request)


class OfficeDocAPIView(DynamicFieldsViewMixin, HtmlModelViewSet):
    """
    公文
    """
    queryset = OfficeDoc.objects.all()
    serializer_class = OfficeDocSerializer
    #permission_classes = (IsAdminUser,)
    renderer_classes = (renderers.BrowsableAPIRenderer, renderers.TemplateHTMLRenderer, renderers.JSONRenderer)


    ordering_fields = ('spinyin', 'publishdate')
    search_fields = ('subject', 'summary')
    filter_fields = ('department', 'category', 'published')
    #template_name = "content/api/notice_detail.html"
    detail_template_name = "content/api/officedoc_detail.html"
    ordering = ["-published"]

    def get_object(self):
        obj = super().get_object()
        read_count_add(obj)
        return obj

    def get_queryset(self):
        qs = super().get_queryset()
        device = self.request.query_params.get('device', None)
        if device:
            dev = Device.objects.get(pk=device)
            qs = qs.filter(Q(department=dev.department) | Q(department__isnull=True)).filter(Q(aimboxs__in=[dev]) | Q(aimboxs=None))
        return qs

    # 创建前处理
    def perform_create(self, serializer):
        serializer.save(createdby=self.request.user)

    @action(methods=["GET"], detail=False)
    def published(self, request):
        '''
        公文已发布
        '''
        self.queryset = OfficeDoc.objects.published()
        return self.list(request)


class VideoAPIView(DynamicFieldsViewMixin, viewsets.ModelViewSet):
    """
    视频
    """
    queryset = Video.objects.all()
    serializer_class = VideoSerializer
    ordering_fields = ('spinyin', 'publishdate')
    search_fields = ('subject', 'summary')
    filter_fields = ('department', 'category', 'published', 'aimboxs')
    #permission_classes = (IsAdminUser,)
    ordering = ["-published"]

    def get_object(self):
        obj = super().get_object()
        read_count_add(obj)
        return obj

    def get_queryset(self):
        qs = super().get_queryset()
        device = self.request.query_params.get('device', None)
        if device:
            dev = Device.objects.get(pk=device)
            qs = qs.filter(Q(department=dev.department) | Q(department__isnull=True)).filter(Q(aimboxs__in=[dev]) | Q(aimboxs=None))
        return qs

    # 创建前处理
    def perform_create(self, serializer):
        serializer.save(createdby=self.request.user)

    @action(methods=["GET"], detail=False)
    def published(self, request):
        '''
        视频已发布
        '''
        self.queryset = Video.objects.published()
        return self.list(request)


class PictureAPIView(DynamicFieldsViewMixin, HtmlModelViewSet):
    """
    图片说
    """
    queryset = Picture.objects.all()
    serializer_class = PictureSerializer
    ordering_fields = ('spinyin', 'publishdate')
    search_fields = ('subject', 'summary')
    filter_fields = ('department', 'category', 'published')
    #permission_classes = (IsAdminUser,)
    renderer_classes = (renderers.BrowsableAPIRenderer, renderers.TemplateHTMLRenderer, renderers.JSONRenderer)
    #template_name = "content/api/notice_detail.html"
    detail_template_name = "content/api/picture_detail.html"
    ordering = ["-published"]

    def get_object(self):
        obj = super().get_object()
        read_count_add(obj)
        return obj

    def get_queryset(self):
        qs = super().get_queryset()
        device = self.request.query_params.get('device', None)
        if device:
            dev = Device.objects.get(pk=device)
            qs = qs.filter(Q(department=dev.department) | Q(department__isnull=True)).filter(Q(aimboxs__in=[dev]) | Q(aimboxs=None))
        return qs

    # 创建前处理
    def perform_create(self, serializer):
        serializer.save(createdby=self.request.user)

    @action(methods=["GET"], detail=False)
    def published(self, request):
        '''
        图片说已发布
        '''
        self.queryset = Picture.objects.published()
        return self.list(request)

        
class CatContentApiViewSet(DynamicFieldsViewMixin, viewsets.ReadOnlyModelViewSet):
    """
    分类内容
        type: OFFICE,TXT_IMG,VIDEO_IMG
    """
    queryset = Content.objects.all()
    serializer_class = ContentSerializer
    #permission_classes = (IsAdminUser,)
    ordering_fields = ('spinyin', 'publishdate')
    search_fields = ('subject', 'summary')
    filter_fields = ('department', 'category', 'published')
    # filter_class = BaseContentFilter

    def get_object(self):
        obj = super().get_object()
        read_count_add(obj)
        return obj

    def get_queryset(self):
        _type = self.request.query_params.get('type', None)
        qs = self.queryset
        device = self.request.query_params.get('device', None)
        if device:
            dev = Device.objects.get(pk=device)
            qs = qs.filter(Q(department=dev.department) | Q(department__isnull=True)).filter(Q(aimboxs__in=[dev]) | Q(aimboxs=None))

        if not _type:
            return qs
        _type = _type.upper()
        if _type == "OFFICE":
            return qs \
                .filter(category__in=[Content.CAT_NOTICE,  Content.CAT_NOTIFY, Content.CAT_OFFICE])
        elif _type == "TXT_IMG":
             return qs \
                 .filter(category__in=[Content.CAT_NEWS, Content.CAT_NOTICE, Content.CAT_NOTIFY, Content.CAT_OFFICE, Content.CAT_PICTURE])
        elif _type == "VIDEO_IMG":
            return qs \
                .filter(category__in=[Content.CAT_VIDEO, Content.CAT_PICTURE])
        else:
            return qs

    ordering = ["-published"]

    @action(methods=["GET"], detail=False)
    def published(self, request):
        '''
        分类内容已发布
        '''
        self.queryset = Content.objects.published()
        return self.list(request)


class ThirdPartyAPIView(DynamicFieldsViewMixin, viewsets.ModelViewSet):
    """
    第三方内容
    ## 说明:

    """
    queryset = ThirdParty.objects.all()
    serializer_class = ThirdPartySerializer
    # permission_classes = (IsAdminUser,)
    # renderer_classes = (renderers.BrowsableAPIRenderer, renderers.TemplateHTMLRenderer,renderers.JSONRenderer)
    search_fields = ('subject', 'summary', 'url', 'token',)
    filter_fields = ('id', 'createdat', 'createdby', 'department', 'updatedat', 'published')
    ordering_fields = ('id', 'createdat', 'createdby', 'department', 'updatedat', 'subject')
    # ordering = []
    # department_filed = '' # 部门过滤字段
    # owner_fileds = [] # 数据所有人过滤字段
    # 数据过滤

    def get_object(self):
        obj = super().get_object()
        read_count_add(obj)
        return obj

    def get_queryset(self):
        qs = super().get_queryset()
        device = self.request.query_params.get('device', None)
        if device:
            dev = Device.objects.get(pk=device)
            qs = qs.filter(Q(department=dev.department) | Q(department__isnull=True)).filter(Q(aimboxs__in=[dev]) | Q(aimboxs=None))
        return qs

    # 创建前处理
    # def perform_create(self, serializer):
    #    serializer.save(from_personnel=personnel)
